package com.example.moonshine.zxing.Fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.moonshine.zxing.Activity.Scoplist;
import com.example.moonshine.zxing.Activity.SuccessActivity;
import com.example.moonshine.zxing.Data.AlData;
import com.example.moonshine.zxing.Data.DresultData;
import com.example.moonshine.zxing.Data.PaintData;
import com.example.moonshine.zxing.Data.ResultScanData;

import com.example.moonshine.zxing.Data.UserpassData;

import com.example.moonshine.zxing.Hepler.DataDBHepler;
import com.example.moonshine.zxing.R;
import com.example.moonshine.zxing.Util.SavePamasInfo;
import com.example.moonshine.zxing.Util.SpostHttp;
import com.example.moonshine.zxing.Util.SureDialog;
import com.google.gson.Gson;

import com.google.gson.JsonSyntaxException;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.util.ArrayList;


/**
 * Created by moonshine on 2018/2/4.
 * 原材料扫码
 */

public class FirstFragment extends Fragment {
    private String path = "http://119.23.219.22:80/element-admin/user/sid-update";
    ResultScanData resultScanData;
    private View view;
    private ImageView btnClick;
    private ImageView btnClicktwo;
    private ImageView btnClickthree;
    private static final String TAG = "MainActivity";
    String Creator;
    DataDBHepler dbHepler;

    String resultStatusCode=null;
    static int flag=1;
    AlData alData;
    DresultData dresultData;
    PaintData paintData;
    private static final int REQUEST_CODE = 1;
    /**
     * fragment的视图
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     *
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fg1, container, false);
        dbHepler = new DataDBHepler(getContext());
        ZXingLibrary.initDisplayOpinion(getActivity());
        initView();
        /**
         * 从数据库里寻找User名
         */
//        ArrayList<UserpassData> DataList = dbHepler.FinduserpassData();
//        final UserpassData data = new UserpassData(DataList.get(0).getId(), DataList.get(0).getUser(),DataList.get(0).getPassword());
//        Log.i(TAG, "数据库的用户名为：" + data.getUser());
//        Creator =data.getUser();
        SavePamasInfo savePamasInfo = new SavePamasInfo();
        Creator=savePamasInfo.getInfo(getContext(),"user","login");
//        Log.i("TAG","用户名"+Creator);
        return view;
    }

    private void initView() {
        btnClicktwo = (ImageView) view.findViewById(R.id.imageView2);
        btnClicktwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), Scoplist.class));
                getActivity().overridePendingTransition(R.anim.up_in, R.anim.up_out);
            }
        });
        btnClickthree = view.findViewById(R.id.imageView3);
        btnClickthree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "暂无其他添加项", Toast.LENGTH_SHORT).show();
            }
        });
        btnClick = (ImageView) view.findViewById(R.id.saoma_btn);
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                getActivity().overridePendingTransition(R.anim.up_in, R.anim.up_out);

            }
        });
    }

public void showDialog() {
    final SureDialog Dialog = new SureDialog(getActivity());
    Dialog.setTitle("消息提示");
    Dialog.setMessage("扫描成功，是否确认出库?");
    Dialog.setYesOnclickListener("确定", new SureDialog.onYesOnclickListener() {
        @Override
        public void onYesClick() {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    SpostHttp spostHttp = new SpostHttp();

                    try {
                        if(flag==1)
                        {

                            resultStatusCode = spostHttp.posthttpresult(alData.getAlId(),alData.getAlWeight(),alData.getUrl(),alData.getAlType(), Creator);
                        }else if (flag==2)
                        {

                            resultStatusCode = spostHttp.Dposthttpresult(dresultData.getDiluentId(),dresultData.getUrl(),Creator);
                        }else
                        {

                            resultStatusCode = spostHttp.Pposthttpresult(paintData.getPaintId(),paintData.getPaintWeight(),paintData.getUrl(),paintData.getpType(),Creator);
                        }
                        Log.i(TAG, "结果为：" + resultStatusCode);
                        if (resultStatusCode.equals("10")) {
                            startActivity(new Intent(getActivity(),SuccessActivity.class));
                            getActivity().overridePendingTransition(R.anim.up_in, R.anim.up_out);
                            Toast.makeText(getActivity(), "出库成功", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getActivity(), "出库失败，服务器故障", Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "服务器故障", Toast.LENGTH_LONG).show();
                    }
                    Looper.loop();
                }
            }).start();
            Dialog.dismiss();
        }
    });
    Dialog.setNoOnclickListener("取消", new SureDialog.onNoOnclickListener() {
        @Override
        public void onNoClick() {
//            Intent intent = new Intent();
//            intent.putExtra("index", "0");
//            intent.setClass(getActivity(), MainActivity.class);
//            startActivity(intent);
            Dialog.dismiss();
        }
    });
    Dialog.show();
}

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Log.i("tag","结果："+result);

                    Gson gson = new Gson();
                    try {
                        alData = gson.fromJson(result,AlData.class);
                        if (alData.getAlId()==null || alData.getAlType()==null)
                        {
                            dresultData = gson.fromJson(result,DresultData.class);
                            if (dresultData.getDiluentId()==null)
                            {
                                paintData = gson.fromJson(result,PaintData.class);
                                flag = 3;
                            } else {
                                flag = 2;
                            }
                        }
                        else {
                            flag =1;
                        }
                        showDialog();
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "扫描错误", Toast.LENGTH_SHORT).show();
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getActivity(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

}